//
//  TaskExt.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/14.
//

import Foundation
class TaskExt {
    //创建任务
    static func createTask() {
        TaskCallExt.instance.doCreate()
        TaskWeeklyLetterExt.instance.doCreate()
        TaskAiDiaryExt.instance.doCreate()
    }
    
    static func checkTask() {
        showLog("开始检测任务")
        ActiveAiExt.checkActive()//检查所有的ai回应
        //检查任务
        TaskCallExt.instance.doCheck()
        TaskWeeklyLetterExt.instance.doCheck()
        TaskAiDiaryExt.instance.doCheck()
    }
    
    //设置明天的0点,传参数不限制毫秒还是秒。
    //返回秒
    static func getTomorrowAt0(_ time: TimeInterval) -> TimeInterval {
        let date = Date(timeIntervalSince1970: TimeInterval(getSecond(time: time)))
        let calendar = Calendar.current
        let startOfToday = calendar.startOfDay(for: date)
        let startOfTomorrow = calendar.date(byAdding: .day, value: 1, to: startOfToday)!
        return startOfTomorrow.timeIntervalSince1970
    }
    
    
    //随机当前时间到-23点59。单位秒
    static func randomTime(_ time: TimeInterval) -> TimeInterval {
        let date = Date(timeIntervalSince1970: getSecond(time: time))
        let calendar = Calendar.current
        
        // 获取当日 23:59:59
        guard let endOfDay = calendar.date(bySettingHour: 23, minute: 59, second: 59, of: date) else {
            return time
        }
        
        // 计算剩余时间差（秒 + 毫秒）
        let timeDifference = endOfDay.timeIntervalSince(date)
        guard timeDifference > 0 else {
            return time
        }
        
        // 生成随机毫秒数（0~999ms）
        let randomMilliseconds = Int.random(in: 0..<Int(timeDifference * 1000))
        
        // 通过时间戳直接添加（更高效）
        let randomDate = date.addingTimeInterval(Double(randomMilliseconds) / 1000.0)
        
        // 确保不超过当日结束时间
        let finalDate = min(randomDate, endOfDay)
        return finalDate.timeIntervalSince1970
    }
    
    /**
     * 删除角色任务
     */
    static func deleteTask(_ roleId : String?) {
        Task {
            let listTaskBean = try await BackupsManager.shared.getDelegateDiary()?.getUnExecutedTask(roleId: roleId, userId: userManager.getUserId(), type: nil) ?? []
            showLog("开始删除角色任务数量:\(listTaskBean.count)")
            for task in listTaskBean {
                showLog("开始删除角色任务:\(String(describing: task.objectId))")
                try await BackupsManager.shared.getDelegateDiary()?.deleteTask(bean: task)
            }
            await MainActor.run {
                //旧任务删除成功后，开始创建新的
                createTask()
            }
        }
    }
}
